<?php
/**
 * Created by PhpStorm.
 * User:王加明
 * Date: 2017-04-13
 * Time: 下午 1:40
 */

namespace app\hongyanche\model;
use think\Db;
use think\Exception;
use think\Model;

class Mall extends Model
{
    private $auth;
    private $tabel = 'mall';
    private $userId;
    private $config;
    var $prefix;
    public function __construct(){
        //检查权限
        $admin = model('admin');
        $auth = $admin -> is('mall');
        if($auth['state']){
            $this->auth = $auth['state'];
        }
        $this->prefix = config('database.prefix');
        //获取user_id
        if (is_null($this->userId)) {
            $user_id = model('user');
            $userId = $this->userId = $user_id->getUserId();
        } else {
            $userId = $this->userId;
        }
        if (!$userId) {
            return;
        }
        $this->config = getConfig('product');
    }
    function getList($filter)
    {
        $demand = 'mall';
        //基础条件
        $order = ["state" => "asc", 'range' => 'asc', 'create_time' => 'desc'];
        $type_id_a = $filter['select'];
        $where = 'state = 1';
        if (isset($filter['page']) && $filter['page'] != '') {
            $pages = $filter['page'];
        }else{
            $pages = 1;
        }
        if ($filter['keywords']) {
            $where .= " and ((name like '%$filter[keywords]%') or spare_parts_code like '%$filter[keywords]%')";
        }
        //labels条件]
        if ($type_id_a) {
            //判断是否为一级标签
            $a = \db('mall_label')->field('category')->where("label_id in($type_id_a) and rank = 0 and state = 1")->cache(true)->select();
            $category = [];
            $b = [];
            foreach ($a as $kk =>$vv){
                $category[] = $vv['category'];
            }
            if($category){
                $categoryid = implode(',',$category);
            }
            if($category){
                $b = \db('mall_label')->field('label_id')->where("category in($categoryid) and state = 1")->cache(true)->select();
            }
            foreach ($b as $k =>$v){
                $b[] = $v['label_id'];
            }
            $labels = array_merge(explode(',',$type_id_a),$b);
            $labels = implode(',',array_unique($labels));
            $where .= " and labels like '%$labels%'";
        }
            if (isset($pages) && isset($maxPerPage)) {
            $type_config = db($demand)->where($where)->order($order)->cache(true)->paginate(20,false,['page'=>$pages]);
            } else {
            $type_config = db($demand)->where($where)->order($order)->cache(true)->paginate(20,false,['page'=>$pages]);
            }
        $page = $type_config->total();
        $type_config = $type_config->items();
        $labels_name = db($demand . '_label')->field('label_id,cn,en')->where("state = 1")->cache(true)->select();
        //再计算一次去掉不存在type_id的
        foreach ($type_config as $k => $v) {
            if (!empty($v['imgurls'])) {
                $img = explode(',', $v['imgurls'])[0];
                $type_config[$k]['imgurl'] = $img;
            }
            if ($v['state'] == 1) {
                $type_config[$k]['released'] = 1;
                unset($type_config[$k]['state']);
            }
            if ($v['labels'] != null) {
                $type_config[$k]['labels'] = explode(',', $v['labels']);
            }
            $price = model('product')->getPriceByProductId($v[$demand . '_id']);
            $type_config[$k]['price_min'] = $price['price_min']/100;
            $type_config[$k]['price_max'] = $price['price_max']/100;
        }
        foreach ($type_config as $k => $v) {
            if (isset($v['labels']) && $v['labels'] && is_array($v['labels'])) {
                if($type_id_a && strpos(',',$type_id_a) !== false && !in_array($type_id_a,$v['labels'])){
                    unset($type_config[$k]);
                    continue;
                }
                foreach ($v['labels'] as $k_k => $v_v) {
                    foreach ($labels_name as $kk => $vv) {
                        if (count($v['labels']) && $vv['label_id'] == $v_v) {
                            //找到他的父级
                            $parents = \db($demand . '_label')->field("cn,rank,category")->where("state = 1 and label_id = $v_v")->cache(true)->find();
                            if($parents['rank'] == 0){
                                $type_config[$k]['label_parents'] = $parents['cn'];
                            }else{
                                //找到父级
                                $type_config[$k]['label_parents'] = db($demand .'_label')->field("cn,rank,category")->where("state = 1 and rank = $parents[category]")->cache(true)->find()['cn'];
                            }
                            $type_config[$k]['labels_name'][$k_k] = $vv['cn'];
                        }
                    }
                }
            }
        }
        foreach ($type_config as $k => $v) {
            if (isset($v['labels_name']) && isset($v['labels'])) {
                $type_config[$k]['labels_name'] = implode(',', $type_config[$k]['labels_name']);
                $type_config[$k]['labels'] = implode(',', $type_config[$k]['labels']);
            } else {
//                unset($type_config[$k]);
            }
        }
        foreach ($type_config as $k =>$v){
            if(count($v) == 1){
                unset($type_config[$k]);
            }
        }
        $result = array('state' => 1, 'data' => array('list' => $type_config),'page'=>$page);
        return $result;
    }
    function getListForAdmin($filter)
    {
        $demand = 'mall';
        //基础条件
        $type_id_a = $filter['select'];
        if (isset($filter['page']) && $filter['page'] != '') {
            $pages = $filter['page'];
        } else {
            $pages = 1;
        }
        //判断权限
//        $labelinfo = db('mall_label')->where("label_id = $filter[label] and state = 1")->find();
//        if(!$labelinfo) return ['state'=>0,'errormsg'=>'您没有权限'];
//        switch ($labelinfo['cn']){
//            case '二手车':
//                if(!\model('admin')->is('Used_car')['state']) return ['state'=>0,'errormsg'=>'您没有权限'];
//                break;
//            case "配件":
//                if(!\model('admin')->is('mall_parts')['state'])return ['state'=>0,'errormsg'=>'您没有权限'];
//                break;
//            default:
//                if(!\model('admin')->is('mall_cust')['state']) return ['state'=>0,'errormsg'=>'您没有权限'];
//                break;
//        }
        $order = ["state" => "desc", 'range' => 'asc', 'create_time' => 'desc'];
        $where = "state != 0";

        if ($filter['keywords']) {
            $where .= " and (name like '%$filter[keywords]%')";
        }
        //labels条件]
        if ($type_id_a && $type_id_a !='请选择') {
            //取出所有子级labels
            $label = db('mall_label')->where("label_id = $type_id_a")->find();
            if($label['rank'] == 0){
                $label_id = db('mall_label')->field('label_id')->where("category = $label[category]")->select();
                foreach ($label_id as $item) {
                    isset($labelid)?$labelid .= "%' or labels like '%".$item['label_id']:$labelid = $item['label_id'];
                }
                $where .=" and labels like '%$labelid%'";
            }else {
                $where .= " and labels like '%$type_id_a%'";
            }
        }
        $type_config = db($demand)->where($where)->order($order)->paginate(20,false,['page'=>$pages]);
        $labels_name = db($demand . '_label')->field('label_id,cn,en')->where("state =1")->select();
        $page = $type_config->render();
        $type_config = $type_config->items();
        $page=preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)","<a href='javascript:ajax_page($1);'>$2</a>",$page);
        $page=str_replace("&laquo;","上一页",$page);
        $page=str_replace("&raquo;","下一页",$page);

        //再计算一次去掉不存在type_id的
        foreach ($type_config as $k => $v) {
            if (!empty($v['imgurls'])) {
                $img = explode(',', $v['imgurls'])[0];
                $type_config[$k]['imgurl'] = $img;
            }
            if ($v['state'] == 1) {
                $type_config[$k]['released'] = $v['state'];
                unset($type_config[$k]['state']);
            } else {
                $type_config[$k]['released'] = 0;
                unset($type_config[$k]['state']);
            }
            if ($v['labels'] != null) {
                $type_config[$k]['labels'] = explode(',', $v['labels']);
            }
            $type_config[$k]['price_min'] = model('product')->getPriceByProductId($v[$demand . '_id'])['price_min'];
            $type_config[$k]['price_max'] = model('product')->getPriceByProductId($v[$demand . '_id'])['price_max'];
            $detail = model('product')->detail_getList(['select' => $v[$demand . '_id']]);
            $type_config[$k]['detail_amount'] = count($detail['data']['list']);
        }
        foreach ($type_config as $k => $v) {
            if (isset($v['labels']) && $v['labels'] && is_array($v['labels'])) {
                if($type_id_a && strpos(',',$type_id_a) !== false && !in_array($type_id_a,$v['labels'])){
                    unset($type_config[$k]);
                    continue;
                }
                foreach ($v['labels'] as $k_k => $v_v) {
                    foreach ($labels_name as $kk => $vv) {
                        if (count($v['labels']) && $vv['label_id'] == $v_v) {
                            $type_config[$k]['labels_name'][$k_k] = $vv['cn'];
                        }
                    }
                }
            }
        }
        foreach ($type_config as $k => $v) {
            if (isset($v['labels_name']) && isset($v['labels'])) {
                $type_config[$k]['labels_name'] = implode(',', $type_config[$k]['labels_name']);
                $type_config[$k]['labels'] = implode(',', $type_config[$k]['labels']);
            } else {
//                unset($type_config[$k]);
            }
        }

        $result = array('state' => 1, 'data' => array('list' => $type_config),'page'=>$page);
        return $result;
    }
    //添加产品
    public function add($data)
    {
        if(!$data['name']) return ['state'=>0,'errormsg'=>'请输入产品名'];
        if(!$data['labels']) return ['state'=>0,'errormsg'=>'请选择类别'];
        $data['state'] = 2;
        $data['user_id'] = $this->userId;
        $data['create_time'] = time();
        $res = \db("mall")->insertGetId($data);
        if(!$res) return ['state'=>0,'errormsg'=>'添加失败,请重新添加'];
        model('action')->add('添加商品','商品名',$data['name']);
        return ['state'=>1,'date'=>['mall_id'=>$res]];
    }
    //修改产品
    public function modify($mall_id,$data)
    {
        if(!$mall_id) return ['state'=>0,'errormsg'=>'请选择产品'];
        if(!$data['name']) return ['state'=>0,'errormsg'=>'请输入产品名'];
        if(!$data['labels']) return ['state'=>0,'errormsg'=>'请选择类别'];
        $data['update_time'] = time();

    }
    //管理员获取今日订单
    public function getListToday($filter){
        //检查是否是管理员操作
        if(!$this->auth){
            return [
                'state' => 0,
                'errormsg' => 'authority incorrect'
            ];
        }
        $mall_order = model('order')->getListToday('mall', $filter);
        if (!$mall_order['state']){
            return $mall_order;
        }
        //统计
        foreach ($mall_order['data']['list'] as $key=>$vaule){
            //咖啡信息
            $detial = json_decode($vaule['detial'],1);
            $num = 0;//本条订单的咖啡数量
            $num_a = '';//单个产品数量
            $mall_info = '';//本条订单的咖啡信息
            foreach ($detial as $item=>$det){
                //此订单出库咖啡的总数
                $num += $det;
                $num_a = $det;
                //获取书本信息
                $tmp= model('product')->getmallInfo($item);
                $mall_info[] = $tmp['data']['info'];
            }
            $mall_order['data']['list'][$key]['account'] = $num;
            $mall_order['data']['list'][$key]['malls'] = $mall_info;
            foreach ($mall_info as $res=>$rs){
                $mall_order['data']['list'][$key]['malls'][$res]['account'] = $num_a;
            }
            $mall_order['data']['list'][$key]['create_time'] = timeString($vaule['create_time']);

            //refund退款金额
            $refund_info = Db::name('pay_refund')->where("order_id",$vaule['order_id'])->select();
            $refund = 0;
            foreach ($refund_info as $k_new => $v_new) {
                $refund += $v_new['total_fee'];
            }
            $mall_order['data']['list'][$key]['refund'] = $refund;
            //支付渠道
            $pay_info = Db::name('pay')->where("order_id",$vaule['order_id'])->find();
            switch ($pay_info['channel']) {
                case 1:
                    $mall_order['data']['list'][$key]['cashpay'] = 1;
                    break;
                case 2:
                    $mall_order['data']['list'][$key]['accountpay'] = 1;
                    break;
                default:
                    switch ((int) ($vaule['channel'] / 100)) {
                        case 1:
                            $mall_order['data']['list'][$key]['wxpay'] = 1;
                            break;
                        case 2:
                            $mall_order['data']['list'][$key]['alipay'] = 1;
                            break;
                    }
            }
            //获取操作员信息
            $admin_user_info = model('user')->getInfoById($vaule['admin_user_id']);
            if ($admin_user_info['user_name']){
                $mall_order['data']['list'][$key]['admin_name'] = $admin_user_info['user_name'];
            }else{
                $mall_order['data']['list'][$key]['admin_name'] = $admin_user_info['user_name'];
            }
            //获取用户信息
            $user_info = model('user')->getInfoById($vaule['user_id']);
            if ($user_info['user_name']){
                $mall_order['data']['list'][$key]['user_name'] = $user_info['user_name'];
                $mall_order['data']['list'][$key]['user_tel'] = $user_info['tel'];
            }
        }
        return [
            'state' => 1,
            'errormsg' => 'ok',
            'data' => [
                'list'=>$mall_order['data']['list'],
                'more'=>$mall_order['data']['more']
            ]
        ];
    }
    //获取mall 订单信息
    public function getMallOrderList($filter){
        //判断权限
        if(!$this->auth){
            return [
                'state'=> 0,
                'errormsg' => 'authority incorrect'
            ];
        }
        if (isset($filter['page'])&&$filter['page'] != '') {
            $pages = $filter['page'];
        } else {
            $pages = 1;
        }

        $mall_order_info = Db::table($this->prefix.'pay')
            ->alias('a')
            ->join($this->prefix.'mall_order b','a.order_id = b.order_id')
            ->join($this->prefix.'mall_detail c','b.detail_id = c.detail_id')
            ->join($this->prefix.'mall d','c.mall_id = d.mall_id')
            ->where('b.state','1')
            ->paginate(12,false,['page'=>$pages]);
        $page = $mall_order_info->render();
        $mall_order_info = $mall_order_info->items();
        $page=preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)","<a href='javascript:ajax_page($1);'>$2</a>",$page);
        $page=str_replace("&laquo;","上一页",$page);
        $page=str_replace("&raquo;","下一页",$page);

        return [
            'state' => 1,
            'data' => [
                'list'=>$mall_order_info,
            ],
            'page'=>$page
        ];
    }
    //用户生成线上订单
    public function orderCreate($detail,$content,$address_id)
    {
        //判断用户是否登录
        if (!$this->userId) {
            return [
                'state' => 0,
                'errormsg' => 'user not find'
            ];
        }
        //判断用户信息是否完善 tel
        $tel = db('user_tel')->field('tel')->where("state = 1 and user_id = $this->userId")->find();
        if(!$tel['tel']) return array('state'=>0,'errormsg'=>'请绑定手机号码');
        //判断是否默认收货地址
        /*$address = db('mall_address')->where("state = 1 and 'default' = 1 and user_id = $this->userId")->find();*/
        if(!$address_id) return array('state'=>0,'errormsg'=>'请选择收货地址');
        if (!$detail) {
            return [
                'state' => 0,
                'errormsg' => 'detail error'
            ];
        }
        $config = $this->config;
        $data['detail'] = $detail;
        $data['user_id'] = $this->userId;
        $data['address_id'] = $address_id;
        $data['state'] = 1;
        $data['class'] = $config['mall']['id'];
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        //计算价格
        $price_info = $this->reckonPrice($detail);
        if(!$price_info['state']){
            return $price_info;
        }
        $data['total_fee'] = $price_info['data']['info']['total_fee'];
        $data['total_fee_original'] = $price_info['data']['info']['total_fee_product'];
        $res = model('order')->add('mall', $data);
        if(!$res['state']){
            return $res;
        }
        $mall_order['detail'] = $detail;
        $mall_order['order_id'] = $res['data']['info']['order_id'];
        $mall_order['user_id'] = $this->userId;
        $mall_order['address_id'] = $address_id;
        $this->businessCreateOrder($mall_order);
        $this->message($res['data']['info']['order_id'],$content);
        //查询地址 查询商品名称 清除购物车
        $address = db('mall_address')->where("address_id = $address_id")->find();
        $addr = $address['address_province'].$address['address_city'].$address['address_district'].$address['address'];
        $detail_key = array_keys(json_decode($detail,1));
        $detail_key = implode(',', $detail_key);
        $detail_id = db('mall_detail')->field('mall_id')->where("detail_id in($detail_key)")->select();
        db('cart')->where("detail_id in($detail_key)")->update(['state'=>0]);
        foreach ($detail_id as $k =>$v){
            isset($mall_id) ? $mall_id .= ','.$v['mall_id'] : $mall_id = $v['mall_id'];
        }
        $mallinfo = db('mall')->field('name')->where("mall_id in($mall_id)")->select();
        foreach ($mallinfo as $k =>$v){
            isset($mall_name) ? $mall_name .= ",".$v['name'] : $mall_name = $v['name'];
        }
        $res['data']['info']['address'] = $addr;
        $res['data']['info']['address_name'] = $address['address_name'];
        $res['data']['info']['mall_name'] = htmlspecialchars_decode($mall_name);
        $res['data']['info']['total_fee'] = $price_info['data']['info']['total_fee'];
        return $res;
    }
    //计算价格
    public function reckonPriceUser($detail)
    {
        //获取detail信息
        $detail_n = json_decode($detail, 1);
        if (!$detail_n) {
            return ['state' => 0, 'errormsg' => 'detail error'];
        }
        //取出id
        $detail_key = array_keys($detail_n);
        $detail_key = implode(',', $detail_key);
        //通过id 查询咖啡信息
        $mall_info = Db::name('mall_detail')->where("detail_id in ($detail_key)")->select();
        if(!$mall_info){
            return ['state'=>0,'errormsg'=>'not find'];
        }
        foreach ($mall_info as $k=>$v){
            if (!$v['price'] or $v['state'] != 1) {
                return [
                    'state' => 0,
                    'errormsg' => 'price error or detail error'
                ];
            }
            $num = $detail_n[$v['detail_id']];
            $price[] = $num * $v['price'];
        }
        $price = array_sum($price);
        if (!$price or $price<=0){
            return [
                'state' => 0,
                'errormsg' => 'reckon_price error'
            ];
        }
        $info['total_fee_original'] = $price;
        $info['total_fee_product'] = $price;
        $info['total_fee'] = $price;
        return [
            'state' => 1,
            'data' => [
                'info' => $info,
            ],
        ];
    }
    //修改mall_order 的状态
    public function mallOrderModify($mall_order_id){
        //判断权限
        if(!$this->auth){
            return [
                'state'=> 0,
                'errormsg' => 'authority incorrect'
            ];
        }
        if (!$mall_order_id){
            return [
                'state' => 0,
                'errormsg' => 'need mall_order_id'
            ];
        }
        $data['state'] = 2;
        $res = Db::name('mall_order')
            ->where('mall_order_id',$mall_order_id)
            ->where('state','1')
            ->update($data);
        if (!$res){
            return [
                'state' => 0,
                'errormsg' => 'update error'
            ];
        }
        return ['state'=>1];
    }
    //计算价格
    public function reckonPrice($detail)
    {
        //通过card_code找到user_id
//        $discount = '';
//        $discount = model('member')->getDiscountByUserId("mall", $this->userId);
        //获取detail信息
        $detail_n = json_decode($detail, 1);
        if (!$detail_n) {
            return ['state' => 0, 'errormsg' => 'detail error'];
        }
        //取出id
        $detail_key = array_keys($detail_n);
        $detail_key = implode(',', $detail_key);
        //通过id 查询咖啡信息
        $mall_info = Db::name('mall_detail')->where("detail_id in ($detail_key)")->select();
        //计算商品价格
        $price_discount = [];
        $price = [];
        //优惠价
        $info['discount_fee'] = 0;
        foreach ($mall_info as $k => $v) {
            if (!$v['price'] or $v['state'] != 1) {
                return [
                    'state' => 0,
                    'errormsg' => 'price error or detail error'
                ];
            }
            $num = $detail_n[$v['detail_id']];
            if($v['deposit']){
                $price[] = $num * $v['deposit'];
            }else{
                if($v['discount']) {
                    $v['discount'] ? $v['discount'] : $v['discount'] = 100;
                    $price[] = $num * ($v['price'] * ($v['discount'] / 100));
                    $info['discount_fee'] += $num * $v['price'] - $num * ($v['price'] * ($v['discount'] / 100));
                }elseif(!$v['discount'] && $v['discount_price']){
                    $price[] = $num * ($v['price'] - $v['discount_price']);
                    $info['discount_fee'] += $num * $v['price']-$num * ($v['price'] - $v['discount_price']);
                }else{
                    $price[] = $num *$v['price'];
                }
            }
            $price_total[] = $num * $v['price'];
        }
        //获取总价格
        $price_total = array_sum($price_total);
        $price = array_sum($price);
        $total_fee = $price;
        //$total_fee = 0;
        if (!$price or $price<=0){
            return [
                'state' => 0,
                'errormsg' => 'reckon_price error'
            ];
        }

        //该会员折扣
//        if ($discount['state']) {
//            //折扣
//            $info['discount'] = $discount['info']['discount'];
//            //user_name
//            $user = model('user')->getInfoById($this->userId);
//            $info['user_name'] = $user['set_name'] ? $user['set_name'] : $user['user_name'];
//            $info['tel'] = isset($user['tel']) ? $user['tel'] : "";
//            //会员等级
//            $info['intro'] = $discount['info']['intro'];
//            //会员卡余额
//            $info['balance'] = model('account')->getBalanceByUserId($this->userId)['data']['balance'];
//            $info['demand'] = $discount['info']['demand'];
//        }
        //最终价格
        $info['total_fee_product'] = $price_total;
        //数量
        $info['total_amount'] = array_sum(array_values($detail_n));
        $info['total_fee'] = $total_fee;
        //返回总价
        return [
            'state' => 1,
            'data' => [
                'info' => $info,
            ],
        ];
    }
    //管理员生成订单
    public function adminOrderCreate($detail,$card_code){
        //判断权限
        if(!$this->auth){
            return [
                'state'=> 0,
                'errormsg' => 'authority incorrect'
            ];
        }
        //判断用户是否登录
        if (!$this->userId){
            return [
                'state' => 0,
                'errormsg' => 'user not find'
            ];
        }
        if (!$detail){
            return [
                'state' => 0,
                'errormsg' => 'detail error'
            ];
        }
        $config = $this->config;
        $data['detail'] = $detail;
        $data['admin_user_id'] = $this->userId;
        $data['state'] = 1;
        $data['class'] = $config['mall']['id'];
        $data['create_time'] = $_SERVER['REQUEST_TIME'];
        //计算价格
        //$where = "b.card_code= $card_code and state=1";
        $user_info = Db::table($this->prefix.'user_member')
            ->alias('a')
            ->join($this->prefix.'user_card b','a.user_id = b.user_id')
            ->where('b.card_code',$card_code)
            ->where('b.state','1')
            ->where('a.state',1)
            ->order('a.class desc')
            ->select();
        $user_id = '';
        if (!empty($user_info)){
            $card_code = $user_info[0]['card_code'];
            $user_id = $user_info[0]['user_id'];
        }else{
            $card_code = '';
        }
        $price_info = $this->reckonPrice($detail,$card_code);
        $data['total_fee'] = $price_info['data']['info']['total_fee'];
        $data['total_fee_original'] = $price_info['data']['info']['total_fee_original'];
        $data['user_id'] = $user_id;
        $res = model('order')->add('mall',$data);
        $this->businessCreateOrder($detail,$res['data']['info']['order_id'],$user_id);
        return $res;
    }
    //业务订单
    private function businessCreateOrder($mall_order)
    {
        if (!$mall_order['detail']) {
            return [
                'state' => 0,
                'errormsg' => 'detail error'
            ];
        }
        if (!$mall_order['order_id']) {
            return [
                'state' => 0,
                'errormsg' => ' order_id need'
            ];
        }
        $detial_arr = json_decode($mall_order['detail'], 1);
        foreach ($detial_arr as $k => $v) {
            $mall_order['detail_id'] = $k;
            if ($this->auth) {
                $mall_order['admin_user_id'] = $this->userId;
            }
            $mall_order['amount'] = $v;
            $mall_order['state'] = 1;
            $mall_order['create_time'] = $_SERVER['REQUEST_TIME'];
            $mall_order['remain'] = $v;
            Db::name('mall_order')->insert($mall_order);
        }
    }
    //获取订单记录
    function getOrderList($filter, $demand = '', $unpaid = false, $channel)
    {
        //权限判断
        if (!$this->auth) {
            return [
                'state' => 0,
                'errormsg' => 'autnhority incorrect'
            ];
        }
        $res = model('order')->getListToday($filter,'mall',$unpaid,$channel);
        if (isset($filter['page']) && $filter['page'] != '') {
            $pages = $filter['page'] - 1;
        } else {
            $pages = 0;
        }
        if (isset($filter['maxPerPage']) && $filter['maxPerPage'] != '') {
            $maxPerPage = $filter['maxPerPage'];
        } else {
            $maxPerPage = 12;
        }
        //当前时间区间
        $order = '';
        foreach ($res['data']['list'] as $k => $v) {
            $tel = Db::name('user_tel')->where("user_id = $v[user_id] and state = 1")->find();
            $order[$k]['tel'] = isset($tel['tel']) ? $tel['tel'] : "";
            $order[$k]['create_time'] = $v['create_time'];
            $order[$k]['total_fee'] = $v['total_fee'];
            $order[$k]['order_id'] = $v['order_id'];
            $order[$k]['user_id'] = $v['user_id'];
            $order[$k]['total_fee_original'] = $v['total_fee_original'];
            $user_info = model('user')->getInfoById($v['user_id']);
            $order[$k]['user_name'] = isset($user_info['set_name']) ? $user_info['set_name'] : userTextDecode($user_info['user_name']);
            if ($v['admin_user_id']) {
                $admin_user_info = model('user')->getInfoById($v['admin_user_id']);
                $order[$k]['admin_user_name'] = isset($admin_user_info['set_name']) ? $admin_user_info['set_name'] : $admin_user_info['user_name'];
            } else {
                $order[$k]['admin_user_name'] = "";
            }
            $message = Db::name('order_message')->where("order_id = $v[order_id] and state = 1")->find();
            if($message){
                $order[$k]['message'] = $message['content'];
            }
            if ($v['detail']) {
                $detail = json_decode($v['detail'], 1);
                $detail_id = implode(',', array_keys($detail));
                $detailList = Db::name('mall_detail')
                    ->alias('a')
                    ->join("mall_order b", "a.detail_id=b.detail_id")
                    ->join("mall c", "c.mall_id=a.mall_id")
                    ->where("a.detail_id in ($detail_id)")
                    ->where("b.order_id", $v['order_id'])
                    ->select();
                foreach ($detailList as $value => $item) {
                    $detail_option = db('mall_detail_option')
                        ->where("detail_id = '$item[detail_id]' and state = 1")
                        ->field('detail_id,detail_option_id,option_name_cn,option_name_en,config_id')->select();
                    foreach ($detail_option as $key => $values) {
                        if ($values['detail_id'] == $detail_id && !empty($values['config_id'])) {
                            $config = db('mall_config')->field('config_id,config_name_cn,config_name_en')->where("config_id = $values[config_id]")->find();
                            if ($values['config_id'] == $config['config_id']) {
                                $detail_option[$key]['config_name_cn'] = $config['config_name_cn'];
                                $detail_option[$key]['config_name_en'] = $config['config_name_en'];
                            }
                            $detailList[$value]['options'][] = $detail_option[$key];
                        }
                    }
                    if (strpos($item['imgurls'], ',')) {
                        $detailList[$value]['imgurl'] = strstr($item['imgurls'], ',', true);  // 从 PHP 5.3.0 起
                    } else {
                        $detailList[$value]['imgurl'] = $item['imgurls'];
                    }
                }
                $order[$k]['detail'] = $detailList;
            }
            //支付渠道
            if (isset($v['channel'])) {
                switch ($v['channel']) {
                    case 1:
                        $order[$k]['cashpay'] = 1;
                        break;
                    case 2:
                        $order[$k]['accountpay'] = 1;
                        break;
                    default:
                        switch ((int)($v['channel'] / 100)) {
                            case 1:
                                $order[$k]['wxpay'] = 1;
                                break;
                            case 2:
                                $order[$k]['alipay'] = 1;
                                break;
                        }
                }
            }else{
                $order[$k]['unpaid'] = 1;
            }
            //计算充值退款金额
            $order_id = $v['order_id'];
            $pay_refund = Db::name('pay_refund')->where("order_id = '$order_id'")->select();

            $refund_total_fee = 0;
            if (isset($pay_refund) && $pay_refund) {
                foreach ($pay_refund as $key => $value) {
                    $refund_total_fee += $value['refund_fee'];
                }
            }
            //充值订单退款
            $order[$k]['refund_fee'] = $refund_total_fee;
        }
        //判断是否有下一页
        $filter['page'] = $pages + 1;
        $type_brand_b = model('order')->getListToday($filter,'mall',$unpaid,$channel);
        if ($type_brand_b) {
            $more = 1;
        } else {
            $more = 0;
        }
        if ($unpaid == false) {
            if ($order) {
                if (isset($data)) {
                    array_multisort(array_column($data, 'create_time'), SORT_ASC, $data);
                    $order = array_merge($data, $order);
                }
            }
        }
        return array('state' => 1, 'data' => array('list' => $order, 'more' => $more, 'maxPerPage' => $maxPerPage));
    }

    //配置
    function config_create($data)
    {
        $user_id = model('user')->getUserId();
        //判断是否是rank为0的
        if($data['labels']) {
            $labellist = db('mall_label')->where("label_id in($data[labels])")->select();
            foreach ($labellist as $k =>$v){
                if($v['rank'] == 0){
                    $label_id[] = $v['label_id'];
                    //查询出所有子集
                    $info = db('mall_label')->where("category = $v[category]")->field('label_id')->select();
                    foreach ($info as $kk =>$vv){
                        $id[] = $vv['label_id'];
                    }
                }
            }
        }
        if(isset($id)) {
            $id = implode(',',$id);
            $data['labels'] = $data['labels'].','.$id;
            $data['labels'] = explode(',',$data['labels']);
            $data['labels'] = implode(',',array_unique($data['labels']));
        }
        $info['state'] = 1;
        if(isset($data['config_template_id']) &&$data['config_template_id']){
            $info['config_template_id'] = $data['config_template_id'];
        }
        if(isset($data['mall_id'])&&$data['mall_id']){
            $info['mall_id'] = $data['mall_id'];
            $info['state'] = 1;
        }
        $info['confing_descripton'] = $data['confing_descripton'];
        $info['user_id'] = $user_id;
        $info['create_time'] = time();
        $info['labels'] = $data['labels'];
        $where = "state = 1 and (labels = ''";
        if ($info['labels']) {
            $where .= " or labels in ($info[labels])";
        }
        $where .= ' )';
        //取出最后一层
        $config_a = db ('mall_config')->where($where)->order('`range` desc')->find();
        if (!$config_a) {
            if ($info['labels']) {
                $info['range'] = 1;
            } else {
                $info['range'] = 0;
            }
        } else {
            $info['range'] = $config_a['range'] + 1;
        }
        //新增一层
        if (!db('mall_config')->insertGetId($info)) {
            return array('state' => 0, 'errormsg' => 'create error', 'errorcode' => '');
        }
        if(isset($data['config_template_id']) &&$data['config_template_id']){
            $template_name = \db('mall_config_template')->where("config_template_id = $data[config_template_id]")->find()['name'];
            model('action')->add('创建配置','模板',$template_name);
        }else {
            if(isset($data['mall_id'])&&$data['mall_id']){
                $mall_name = \db('mall')->where("mall_id = $data[mall_id]")->find()['name'];
                model('action')->add('创建配置','商品',$mall_name);
            }else{
                model('action')->add('创建配置');

            }
        }
        return array('state' => 1, 'errormsg' => 'ok');
    }

    //删除配置
    function config_remove($config_id)
    {
        if (!$config_id > 0) {
            return array('state' => 0, 'errormsg' => 'config id incorrect', 'errorcode' => '');
        }
        $data['state'] = 0;
        $where = "config_id in($config_id)";
        if(!model('admin')->is('mall',1)['state']) {
            $list = db('mall_config')->where($where)->select();
            $config_ids = explode(',', $config_id);
            foreach ($list as $k => $v) {
                if ($v['config_template_id']) {
                    foreach ($config_ids as $kk => $vv) {
                        if ($vv == $v['config_id']) {
                            unset($config_ids[$kk]);
                        }
                    }
                }
            }
            $config_id = implode(',',$config_ids);
        }
        $where = "config_id in($config_id)";
        $data['user_id'] = model('user')->getUserId();
        $res = db('mall_config')->where($where)->update($data);
        //删除配置后对应的配置参数也该删除
        if ($res) {
            db('mall_config_option')->where($where)->update($data);
        }
        $config_name = \db('mall_config')->field('config_name_cn')->where("config_id in ($config_id)")->select();
        foreach ($config_name as $k =>$v){
            $name[] = $v['config_name_cn'];
        }
        $name = implode(',',$name);
        model('action')->add('删除配置','配置名字',$name);
        return array('state' => 1, 'errormsg' => 'ok', 'errorcode' => '');
    }
    function config_detail_remove($config_id)
    {
        if (!$config_id > 0) {
            return array('state' => 0, 'errormsg' => 'config id incorrect', 'errorcode' => '');
        }
        $where = "config_id in($config_id)";
        $list = db('mall_config')->where($where)->select();
        $config_ids = explode(',', $config_id);
        foreach ($list as $k => $v) {
            if ($v['config_template_id']) {
                foreach ($config_ids as $kk => $vv) {
                    if ($vv == $v['config_id']) {
                        unset($config_ids[$kk]);
                    }
                }
            }
        }
        $config_id = implode(',',$config_ids);
        $data['state'] = 0;
        $where = "config_id in($config_id)";
        $data['user_id'] = model('user')->getUserId();
        $res = db('mall_config')->where('config_template_id is null')->where($where)->update($data);
        //删除配置后对应的配置参数也该删除
        if ($res) {
            db('mall_config_option')->where($where)->update($data);
        }
        $config_name = \db('mall_config')->field('config_name_cn')->where("config_id in ($config_id)")->select();
        foreach ($config_name as $k =>$v){
            $name[] = $v['config_name_cn'];
        }
        $name = implode(',',$name);
        model('action')->add('删除配置','配置名字',$name);
        return array('state' => 1, 'errormsg' => 'ok', 'errorcode' => '');
    }
    //配置描述
    public function config_descripton($config_id,$config_descripton)
    {
        if(!$config_id) return array('state'=>0,'errormsg'=>'请选择一个配置');
        $data['config_descripton'] = $config_descripton;
        $res = db('mall_config')->where("config_id = $config_id")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'添加描述失败'];
        $conifg_name = \db('mall_config')->where("config_id = $config_id")->find()['config_name_cn'];
        model('action')->add('添加配置描述',$conifg_name.'的描述内容',$config_descripton);
        return ['state'=>1,'errormsg'=>'ok'];
    }
    function config_release($config_id, $release)
    {
        if(!model('admin')->is('mall',1)['state']) return array('state'=>0,'errormsg'=>'您没有权限');
        if (!$config_id > 0) {
            return array('state' => 0, 'errormsg' => 'config id incorrect', 'errorcode' => '');
        }
        if ($release) {
            $data['state'] = 1;
        } else {
            $data['state'] = 2;
        }
        $where = "config_id in($config_id)";
        $data['user_id'] = model('user')->getUserId();
        $res = db('mall_config')->where($where)->update($data);
        if (!$res) {
            return array('state' => 0, 'errormsg' => 'release error');
        }
        $conifg_name = \db('mall_config')->where("config_id = $config_id")->find()['config_name_cn'];
        if($release){
            model('action')->add('开放配置','配置名称',$conifg_name);
        }else{
            model('action')->add('关闭配置','配置名称',$conifg_name);
        }
        return array('state' => 1, 'errormsg' => 'ok', 'errorcode' => '');
    }

    function config_rename($type_config_id, $config_name, $lang,$describe)
    {
        $user_id = model('user')->getUserId();
        if (!$lang) {
            $lang = 'cn';
        }
        if (!$type_config_id > 0) {
            return array('state' => 0, 'errormsg' => 'type_config id incorrect', 'errorcode' => '');
        }
        if(!model('admin')->is('mall',1)['state']) {
            $where = "config_id = '$type_config_id' and user_id = $this->userId";
        }else{
            $where = "config_id = '$type_config_id'";
        }
        $data['config_name_' . $lang] = $config_name;
        $data['user_id'] = $user_id;
        $data['describe'] = $describe;
        //原名称
        $configname = \db('mall_config')->where("config_id = $type_config_id")->find()['config_name_cn'];
        db('mall_config')->where($where)->update($data);
        model('action')->add('配置重命名',$configname,$config_name);
        return array('state' => 1, 'errorcode' => 'ok',);
    }
    function config_adminList($config_template_id)
    {
        if(!$config_template_id) return ['state'=>1,'data'=>[]];
        $template = db('mall_config_template')->where("$config_template_id = config_template_id")->find();
        if(!$template) return ['state'=>1,'data'=>[]];
        $configlist = db('mall_config')->where("state != 0 and config_template_id = $config_template_id")->select();
        $config_optionlist = db('mall_config_option')
            ->where("state = 1")
            ->field('config_id,config_option_id,option_name_cn,option_name_en')
            ->order('`range`,option_name_cn')->select();
        $labels_name = db('mall_label')->field('label_id,cn,en')->where("state =1")->select();
        foreach ($configlist as $k => $v) {
            $configlist[$k]['config_template_id'] =$config_template_id;
            $configlist[$k]['template_name'] = $template['name'];
            if ($v['state'] == 1) {
                $configlist[$k]['released'] = 1;
            } else {
                $configlist[$k]['released'] = 0;
            }
            unset($configlist[$k]['state']);
        }
        foreach ($configlist as $k => $v) {
            foreach ($config_optionlist as $kk => $vv) {
                if ($v['config_id'] == $vv['config_id']) {
                    $configlist[$k]['config_options'][] = $vv;
                }
            }
        }
        foreach ($configlist as $k => $v) {
            if ($v['labels'] != null) {
                $configlist[$k]['labels'] = explode(',', $v['labels']);
            }
        }
        foreach ($configlist as $k => $v) {
            if (is_array($v['labels'])) {
                foreach ($v['labels'] as $k_k => $v_v) {
                    foreach ($labels_name as $kk => $vv) {
                        if (count($v['labels']) && $vv['label_id'] == $v_v) {
                            $configlist[$k]['labels_name'][$k_k] = $vv['cn'];
                        }
                    }
                }
                $configlist[$k]['labels'] = implode(',', $configlist[$k]['labels']);
            }
            if (isset($configlist[$k]['labels_name'])) {
                $configlist[$k]['labels_name'] = implode(',', $configlist[$k]['labels_name']);
            }
        }
//            $res['config'] = $configlist;
//            dump($configlist);die;
        return array('state'=>1,'data'=>array('list'=>$configlist));
    }
    function config_list($config_template_id,$mall_id)
    {
        if(!$config_template_id && !$mall_id) return ['state'=>1,'data'=>[]];
//        $template = db('mall_config_template')->where("$config_template_id = config_template_id")->find();
//        if(!$template) return ['state'=>1,'data'=>[]];
        $where = "mall_id = $mall_id ";
        if($config_template_id) $where.=" or config_template_id = $config_template_id";
        $configlist = db('mall_config')->where('state = 1')->where($where)->order('`range`,create_time desc')->select();
        $config_optionlist = db('mall_config_option')
            ->where("state = 1")
            ->field('config_id,config_option_id,option_name_cn,option_name_en')
            ->order('`range`,option_name_cn')->select();
        $labels_name = db('mall_label')->field('label_id,cn,en')->where("state =1")->select();
        foreach ($configlist as $k => $v) {
            if ($v['state'] == 1) {
                $configlist[$k]['released'] = 1;
            } else {
                $configlist[$k]['released'] = 0;
            }
            unset($configlist[$k]['state']);
        }
        foreach ($configlist as $k => $v) {
            foreach ($config_optionlist as $kk => $vv) {
                if ($v['config_id'] == $vv['config_id']) {
                    $configlist[$k]['config_options'][] = $vv;
                }
            }
        }
        foreach ($configlist as $k => $v) {
            if ($v['labels'] != null) {
                $configlist[$k]['labels'] = explode(',', $v['labels']);
            }
        }
        foreach ($configlist as $k => $v) {
            if (is_array($v['labels'])) {
                foreach ($v['labels'] as $k_k => $v_v) {
                    foreach ($labels_name as $kk => $vv) {
                        if (count($v['labels']) && $vv['label_id'] == $v_v) {
                            $configlist[$k]['labels_name'][$k_k] = $vv['cn'];
                        }
                    }
                }
                $configlist[$k]['labels'] = implode(',', $configlist[$k]['labels']);
            }
            if (isset($configlist[$k]['labels_name'])) {
                $configlist[$k]['labels_name'] = implode(',', $configlist[$k]['labels_name']);
            }
        }
//            $res['config'] = $configlist;
//            dump($configlist);die;
        return array('state'=>1,'data'=>array('list'=>$configlist));
    }


    //配置模板
    public function config_template_create()
    {
        if(!$this->userId) return array('state'=>0,'errormsg'=>'请登录');
        if(!model('admin')->is('mall',1)['state']) return array('state'=>0,'errormsg'=>'您没有权限');
//        if(!$data['name']) return array('state'=>0,'errormsg'=>'请命名模板');
//        $data['create_time'] = time();
//        $data['user_id'] = $this->userId;
//        $data['state'] = 2;
//        $res = db('mall_config_template')->insert($data);
//        if(!$res) return array('state'=>0,'errormsg'=>'模板创建失败');
        $data['state'] = 2;
        $data['create_time'] = time();
        $data['user_id'] = $this->userId;
        $res = db('mall_config_template')->insertGetId($data);
        if(!$res) return ['state'=>0,'errormsg'=>'模板创建失败'];
        model('action')->add('创建模板');
        return array('state'=>1,'data'=>['config_template_id'=>$res]);
    }
    public function config_template_remove($config_template_id)
    {
        if(!$this->userId) return array('state'=>0,'errormsg'=>'请登录');
        if(!model('admin')->is('mall',1)['state']) return array('state'=>0,'errormsg'=>'您没有权限');
        if(!$config_template_id) return array('state'=>0,'errormsg'=>'请选择一个模板');
        $data['state'] = 0;
        $res = db('mall_config_template')->where("config_template_id in($config_template_id)")->update($data);
        if(!$res) return array('state'=>0,'errormsg'=>'模板删除失败');
        $temname = db('mall_config_template')->field('name')->where("config_template_id in($config_template_id)")->select();
        foreach ($temname as $k =>$v){
            $name[] = $v['name'];
        }
        $name = implode(',',$name);
        model('action')->add('删除模板','模板名称',$name);
        return array('state'=>1,'errormsg'=>'模板删除成功');
    }
    public function config_template_modify($config_template_id,$newname)
    {
        if(!$this->userId) return array('state'=>0,'errormsg'=>'请登录');
        if(!model('admin')->is('mall',1)['state']) return array('state'=>0,'errormsg'=>'您没有权限');
        if(!$config_template_id) return array('state'=>0,'errormsg'=>'请选择一个模板');
        $data['name'] = $newname;
        //原模板名
        $namey = \db('mall_config_template')->field('name')->where("config_template_id = $config_template_id")->find()['name'];
        $res = db('mall_config_template')->where("config_template_id = $config_template_id")->update($data);
        if(!$res) return array('state'=>0,'errormsg'=>'模板命名失败');
        $name = \db('mall_config_template')->field('name')->where("config_template_id = $config_template_id")->find()['name'];
        model('action')->add('修改模板名',$namey,$name);
        return array('state'=>1,'errormsg'=>'模板命名成功');
    }
    public function config_template_list()
    {
        if(!$this->userId) return array('state'=>0,'errormsg'=>'请登录');
        //查询模板
        if(!model('admin')->is('mall',1)['state']) {
            $res = db('mall_config_template')->where('state = 1')->order('`range`,create_time desc')->select();
        }else{
            $res = db('mall_config_template')->where('state != 0')->order('`range`,create_time desc')->select();
        }
        foreach ($res as $k =>$v){
            if($v['state'] == 1){
                $res[$k]['released'] = 1;
            }else {
                $res[$k]['released'] = 0;
            }
//                unset($res[$k]['state']);
        }
        if(!$res) return array('state'=>1,'data'=>[]);
        return array('state'=>1,'data'=>['list'=>$res]);
    }
    public function config_template_release($config_template_id,$release)
    {
        if(!$this->userId) return array('state'=>0,'errormsg'=>'请登录');
        if(!model('admin')->is('mall',1)['state']) return ['state'=>0,'errormsg'=>'您没有权限'];
        if(!$config_template_id) return ['state'=>0,'errormsg'=>'请选择一个模板'];
        if($release){
            $data['state'] = 1;
        }else{
            $data['state'] = 2;
        }
        $res = db('mall_config_template')->where("config_template_id = $config_template_id")->update($data);
        if(!$res) return ['state'=>0,'errormsg'=>'关闭失败'];
        $name = \db('mall_config_template')->field('name')->where("config_template_id = $config_template_id")->find()['name'];
        if($release){
            model('action')->add('开放模板','模板名',$name);
        }else{
            model('action')->add('关闭模板','模板名',$name);
        }

        return array('state'=>1,'errormsg'=>'ok');
    }
    function config_template_range($ranges)
    {
        if (!$ranges) return ['state' => 0, 'range error'];
        $ranges = explode(",", $ranges);
        foreach ($ranges as $range => $config_template_id) {
            $where = ['config_template_id' => $config_template_id, 'state' => ['<>', 0]];
            $update = ['range' => $range];
            db( 'mall_config_template')->where($where)->update($update);
        }
        return ['state' => 1];
    }


    public function orderReday($mall_order_id,$order_id)
    {
        if(!$this->auth){
            return [
                'state' => 0,
                'errormsg' => 'autnhority incorrect'
            ];
        }
        if($mall_order_id){
            $mall = Db::name('mall_order')->where('mall_order_id',$mall_order_id)->find();
            if(!$mall['remain']){
                return ['state'=>0,'errormsg'=>'Has been completed'];
            }
            $ret = Db::name('mall_order')->where('mall_order_id',$mall_order_id)->setDec('remain');
            if(!$ret){
                return ['state'=>0,'errormsg'=>'updata error'];
            }
            return ['state'=>1];
        }
        if($order_id){
            $mall = Db::name('mall_order')->where('order_id',$order_id)->select();
            $arr = [];
            foreach ($mall as $v){
                $arr[] = $v['remain'];
            }
            if(!array_sum($arr)){
                return ['state'=>0,'order has been completed'];
            }
            $ret = Db::name('mall_order')->where('order_id',$order_id)->update(['remain'=>0]);
            if(!$ret){
                return ['state'=>0,'errormsg'=>'updata error'];
            }
            return ['state'=>1];
        }
    }
    public function orderNew($time){
        if(!$time){
            return ['state'=>0,'errormsg'=> 'time error'];
        }
        $order = Db::name('pay')
            ->alias('a')
            ->join('order b','a.order_id = b.order_id')
            ->field('b.create_time')
            ->where("b.create_time >= $time")
            ->select();
        if (!count($order)){
            return ['state'=>0];
        }
        return ['state'=>1];
    }


    //左侧导航栏
    public function suggest(){
        $demand = "mall";
        $where = "state = '1'";
        $result = [];
        $label = \think\Db::name($demand."_label")->where($where)
            ->order('category,rank')->select();

        foreach ($label as $k => $v) {
            if ($v['rank'] == 0) {
                $result[$v['category']]['category_cn'] = $v['cn'];
                $result[$v['category']]['label_id'] = $v['label_id'];
                $result[$v['category']]['category_en'] = $v['en'];
                $result[$v['category']]['category_text'] = $v['cn'] . ' ' . $v['en'];
            } else {
                $result[$v['category']]['labels'][] = $v;
            }
        }
        foreach ($result as $key => $value) {
            if(isset($value['labels'])) {
                foreach ($value['labels'] as $key_n => $value_n) {
                    $result[$key]['labels'][$key_n]['label_en'] = $value_n['en'];
                    $result[$key]['labels'][$key_n]['label_cn'] = $value_n['cn'];
                    $result[$key]['labels'][$key_n]['label_id'] = $value_n['label_id'];
                    $result[$key]['labels'][$key_n]['label_text'] = $value_n['cn'] . ' ' . $value_n['en'];
                    unset($result[$key]['labels'][$key_n]['en'], $result[$key]['labels'][$key_n]['cn'], $result[$key]['labels'][$key_n]['state'], $result[$key]['labels'][$key_n]['rank'], $result[$key]['labels'][$key_n]['category'], $result[$key]['labels'][$key_n]['user_id']);
                }
            }
        }
        foreach ($result as $k=>$v){
            foreach(isset($v['labels'])?$v['labels']:[] as $kk=>$vv){
                $where = "(labels like '%$vv[label_id]%' or labels like '%$v[label_id]%') and state=1 and suggest=1";
                $res = Db::name($demand)->field('mall_id,name,imgurls,labels')->where($where)->select();
                foreach($res as $kkk=>$vvv) {
                    if (in_array($vv['label_id'],explode(',',$vvv['labels']))) {
                        $urls = explode(",", $vvv['imgurls']);
                        $vvv['imgurl'] = count($urls) ? $urls[0] : "";
                        unset($vvv['imgurls']);
                        $result[$k]['list'][] = $vvv;
//                    unset($result[$k]['labels'][$kk]['imgurls']);
                    }
                }
                //$result[$k]['list'][] = $res;
            }
        };
        foreach ($result as $k=>$v){
            unset($result[$k]['labels']);
        }
        foreach ($result as $k =>$v){
            if(isset($v['list'])){
                $result[$k]['list'] = array_chunk($v['list'],3);
            }
        }
        return [
            'state'=>1,
            'data'=>[
                'rank'=>$result
            ]
        ];
    }
    //左侧三级导航栏
    public function suggest_menu(){
        $demand = "mall";
        $where = "state = '1'";
        $result = [];
        $label = \think\Db::name($demand."_label")->where($where)
            ->order('category,rank')->select();
        foreach ($label as $k => $v) {
            if ($v['rank'] == 0) {
                $result[$v['category']]['category_cn'] = $v['cn'];
                $result[$v['category']]['category_en'] = $v['en'];
                $result[$v['category']]['category_text'] = $v['cn'] . ' ' . $v['en'];
            } else {
                $result[$v['category']]['labels'][] = $v;
            }
        }
        foreach ($result as $key => $value) {
            if(isset($value['labels'])) {
                foreach ($value['labels'] as $key_n => $value_n) {
                    $result[$key]['labels'][$key_n]['label_en'] = $value_n['en'];
                    $result[$key]['labels'][$key_n]['label_cn'] = $value_n['cn'];
                    $result[$key]['labels'][$key_n]['label_id'] = $value_n['label_id'];
                    $result[$key]['labels'][$key_n]['label_text'] = $value_n['cn'] . ' ' . $value_n['en'];
                    unset($result[$key]['labels'][$key_n]['en'], $result[$key]['labels'][$key_n]['cn'], $result[$key]['labels'][$key_n]['state'], $result[$key]['labels'][$key_n]['rank'], $result[$key]['labels'][$key_n]['category'], $result[$key]['labels'][$key_n]['user_id']);
                }
            }
        }
        foreach ($result as $k=>$v){
            foreach($v['labels'] as $kk=>$vv){
                $where = "labels like '%".$vv['label_id']."%' and state=1 and suggest=1";
                $res = Db::name($demand)->field('mall_id,name,imgurls')->where($where)->select();
                foreach($res as $kkk=>$vvv){
                    $res[$kkk]['imgurl'] = explode(',',$vvv['imgurls'])[0];
                    $result[$k]['labels'][$kk]['imgurl'] = explode(',',$vvv['imgurls'])[0];
                    unset($res[$kkk]['imgurls']);
                    $result[$k]['labels'][] = $res[$kkk];
                }
            }
        };
        return [
            'state'=>1,
            'data'=>[
                'rank'=>$result
            ]
        ];
    }
    //根据mall_id获取产品详情
    public function getMallInfoById($mall_id,$admin_only = 0)
    {
        if($mall_id<0){
            return ['state'=>0,'errormsg'=>'Parameter error'];
        }
        if(!$mall_id){
            return ['state'=>0,'errormsg'=>'need mall_id'];
        }
        $mallInfo = Db::name('mall')->where("mall_id = $mall_id and state = 1")->find();
        if(!$mallInfo){
            return ['state'=>0,'errormsg'=>'not find brand exist'];
        }
        $label_id = $mallInfo['labels'];
        $labels = [];
        if($label_id){
            $labels = Db::name('mall_label')->where("label_id in($label_id) and state = 1")->select();
        }
        $labels_name = [];
        foreach ($labels as $key=>$value){
            if(strpos($value['cn'], '二手') !== false){
                $mallInfo['two'] = 1;
            }
            if(strpos($value['cn'], '配件') !== false){
                $mallInfo['pei'] = 1;
            }
            $labels_name[] = $value['cn'];
        }
        $mallInfo['labels_name'] = implode(',',$labels_name);
        $detailList = Db::name('mall_detail')->where("mall_id = $mallInfo[mall_id] and state = 1 and isnull(admin_only)")->select();
        foreach ($detailList as $value => $item) {
            $detail_option = db('mall_detail_option')
                ->where("detail_id = '$item[detail_id]' and state = 1")
                ->field('detail_id,detail_option_id,option_name_cn,option_name_en,config_id')->select();
            foreach ($detail_option as $key => $values) {
                if (!empty($values['config_id'])) {
                    $config = db('mall_config')->field('config_id,config_name_cn,config_name_en,range,config_descripton')->where("config_id = $values[config_id]")->find();
                    if ($values['config_id'] == $config['config_id']) {
                        $detail_option[$key]['config_name_cn'] = $config['config_name_cn'];
                        $detail_option[$key]['config_name_en'] = $config['config_name_en'];
                        $detail_option[$key]['config_descripton'] = $config['config_descripton'];
                        $detail_option[$key]['range'] = $config['range'];
                    }
                }
            }
            array_multisort(array_column($detail_option,'range'),SORT_ASC,$detail_option);
            $detailList[$value]['options'] = $detail_option;
        }
        $mallInfo['imgurls'] = explode(',',$mallInfo['imgurls']);
        $mallInfo['imgurl'] = $mallInfo['imgurls'][0];

        $mallInfo['detail'] = $detailList;
        return ['state'=>1,'data'=>['info'=>$mallInfo]];
    }
    //首页推荐
    public function product_suggest($mall_id,$suggest){
        if(!$this->auth){
            return [
                'state'=> 0,
                'errormsg' => 'authority incorrect'
            ];
        }
        $where = "mall_id = $mall_id";
        $data['suggest']  = $suggest;
        $res = Db::name('mall')->where($where)->update($data);
        if($res){
            return  [
                'state'=>1,
                'errormsg'=>'Set success'
            ];
        }
        return [
            'state'=>0,
            'errormsg'=>'Set success'
        ];
    }

    //获取某个订单的详细信息
    public function getOrderInfo($order_id)
    {
        //判断order_id是否接到
        if (!$order_id) {
            return array('state' => 0, 'errormsg' => 'need order_id');
        }
        $order_info = db('order')->where("order_id = '$order_id'")->find();
        //判断是否存在或已删除
        $orderinfo = model('order')->getInfo($order_id);
        if (!$orderinfo || $orderinfo['state'] == 0) {
            return array('state' => 0, 'errormsg' => 'order_id no exist');
        }
        $orderinfo = $orderinfo['data']['info'];
        $pay_in = getConfig('product')['mall']['pay_in'];
        $channel = db('pay')->where("order_id = $orderinfo[order_id]")->find();
        if($channel){
            switch ($channel['channel']) {
                case 1:
                    $orderinfo['cashpay'] = 1;
                    break;
                case 2:
                    $orderinfo['accountpay'] = 1;
                    break;
                default:
                    switch ((int)($channel['channel'] / 100)) {
                        case 1:
                            $orderinfo['wxpay'] = 1;
                            break;
                        case 2:
                            $orderinfo['alipay'] = 1;
                            break;
                    }
            }
        }else{
            if($orderinfo['total_fee'] !=0) {
                if (time() - $orderinfo['create_time'] > $pay_in) {
                    $orderinfo['overdue'] = 1;
                } else {
                    $orderinfo['unpaid'] = 1;
                }
            }else{
                $orderinfo['free'] = 1;
            }
        }
        $pay_refund = db('pay_refund')->where("order_id = '$orderinfo[order_id]'")->select();

        $refund_total_fee = 0;
        if (isset($pay_refund) && $pay_refund) {
            foreach ($pay_refund as $key => $value) {
                $refund_total_fee += $value['refund_fee'];
            }
        }
        //充值订单退款
        $orderinfo['refund_fee'] = $refund_total_fee;

        $user_info = model('user')->getInfoById($order_info['user_id']);
        $orderinfo['user_name'] = isset($user_info['set_name'])? $user_info['set_name']:$user_info['user_name'];
        $admin_user_info = model('user')->getInfoById($order_info['admin_user_id']);
        $orderinfo['admin_user_id'] = $admin_user_info['user_id'];
        $orderinfo['admin_user_name'] = isset($admin_user_info['set_name'])? $admin_user_info['set_name']:$admin_user_info['user_name'];
        if ($orderinfo['detail']) {
            $detail = json_decode($orderinfo['detail'], 1);
            $orderinfo['total_amount'] = 0;
            $detail_id = implode(',', array_keys($detail));
            $detailList = db('mall_detail')
                ->alias('a')
                ->field('a.detail_id,imgurls,price,name,mall_order_id,c.create_time')
                ->join("mall_order b", "a.detail_id=b.detail_id")
                ->join("mall c", "c.mall_id=a.mall_id")
                ->where("a.detail_id in ($detail_id)")
                ->where("b.order_id", $order_id)
                ->order('b.create_time desc')
                ->select();
            foreach ($detailList as $value => $item) {
                foreach ($detail as $k =>$v){
                    if($k == $item['detail_id']){
                        $detailList[$value]['amount'] = $v;
                    }
                }
                $detail_option = db('mall_detail_option')
                    ->where("detail_id = '$item[detail_id]' and state = 1")
                    ->field('detail_id,detail_option_id,option_name_cn,option_name_en,config_id')->select();
                foreach ($detail_option as $key => $values) {
                    if ($values['detail_id'] == $detail_id && !empty($values['config_id'])) {
                        $config = db('mall_config')->field('config_id,config_name_cn,config_name_en')->where("config_id = $values[config_id]")->find();
                        if ($values['config_id'] == $config['config_id']) {
                            $detail_option[$key]['config_name_cn'] = $config['config_name_cn'];
                            $detail_option[$key]['config_name_en'] = $config['config_name_en'];
                        }
                        $detailList[$value]['options'][] = $detail_option[$key]['config_name_cn'] . ':' . $detail_option[$key]['option_name_cn'];
                    }
                }
                if (strpos($item['imgurls'], ',')) {
                    $detailList[$value]['imgurl'] = strstr($item['imgurls'], ',', true);  // 从 PHP 5.3.0 起
                } else {
                    $detailList[$value]['imgurl'] = $item['imgurls'];
                }
            }
            foreach ($detailList as $k => $v) {
                if (isset($v['options'])) {
                    $detailList[$k]['options'] = implode(',', $v['options']);
                }
                $detailList[$k]['class'] = 'mall';
            }
            $orderinfo['detail'] = $detailList;
        }
        return array('data' => array('info' => $orderinfo), 'state' => 1);
    }
    //用户查询订单
    public function userOrderList($order_id,$user_id=null)
    {
        $order =Db::name('order')
            ->where("order_id in ($order_id)")
            ->order('create_time desc')
            ->select();
        foreach ($order as $key=>$value){
            $orderInfo = $this->getOrderInfo($value['order_id'],$user_id);
            if($orderInfo['state']){
                $order[$key] = $orderInfo['data']['info'];
            }

        }
        return ['state'=>1,'data'=>['list'=>$order]];
    }

    //用户留言
    public function message($order_id,$content)
    {
        if(!$this->userId){
            return ['state'=>0,'errormsg'=> 'not user login'];
        }
        if(!$order_id){
            return ['state'=>0,'errormsg'=>'need order_id'];
        }
        $data['order_id'] = $order_id;
        $data['user_id'] = $this->userId;
        $data['create_time'] = time();
        $data['content'] = $content;
        $data['state'] = 1;
        $res = Db::name('order_message')->insertGetId($data);
        if(!$res){
            return ['state'=>0,'errormsg'=>'insert error'];
        }
        return ['state'=>1];
    }

    //获取退款订单
    public function getRefundList($demand, $fiter, $chnnel)
    {
        $refund = model('order')->getRefundList($demand, $fiter, $chnnel);
        foreach ($refund['data']['list'] as $k => $v) {
            //支付渠道
            switch ($v['channel']) {
                case 1:
                    $refund['data']['list'][$k]['cashpay'] = 1;
                    break;
                case 2:
                    $refund['data']['list'][$k]['accountpay'] = 1;
                    break;
                default:
                    switch ((int)($v['channel'] / 100)) {
                        case 1:
                            $refund['data']['list'][$k]['wxpay'] = 1;
                            break;
                        case 2:
                            $refund['data']['list'][$k]['alipay'] = 1;
                            break;
                    }
            }
            //产品信息
            //查找detail信息
            if (!is_null($v['detail'])) {
                $detail_n = json_decode($v['detail'], 1);
                $detail_key = array_keys($detail_n);

                $detail_key = implode(',', $detail_key);
                $product_info = db("mall_detail")->where("detail_id in ($detail_key)")->select();
                $detail = $product_info[0]['detail_id'];
                $detail_info = db('mall_detail')->alias('d')
                    ->join("mall c", "c.mall_id = d.mall_id")
                    ->where("detail_id = '$detail'")->select();
                $refund['data']['list'][$k]['summary'] = $detail_info[0]['name'];
                $refund['data']['list'][$k]['create_time'] = $v['create_time'];
                //admin_user_name
                $user_info = model('user')->getInfoById($v['user_id']);
                $refund['data']['list'][$k]['user_name'] = isset($user_info['set_name']) ? $user_info['set_name'] : userTextDecode($user_info['user_name']);
                $refund['data']['list'][$k]['tel'] = isset($user_info['tel']) ? $user_info['tel'] : "";
                $admin_user_info = model('user')->getInfoById($v['admin_user_id']);
                $refund['data']['list'][$k]['admin_user_name'] = $admin_user_info['set_name'] ? $admin_user_info['set_name'] : $admin_user_info['user_name'];
                $num = null;
                foreach ($detail_n as $key => $value) {
                    $num += $value;
                }
                $refund['data']['list'][$k]['account'] = $num;
            } else {
                $admin_user_info = model('user')->getInfoById($v['admin_user_id']);
                $refund['data']['list'][$k]['admin_user_name'] = $admin_user_info['set_name'] ? $admin_user_info['set_name'] : $admin_user_info['real_name'];
            }
        }
        return $refund;
    }


    //月报表
    public function report($data)
    {
        header("Content-type:application/vnd.ms-excel;charset:UTF-8");
        $name = "hongyanche_" . "mall";
        if ($data['start'] && $data['end']) {
            $startime = strtotime($data['start']);
            $endtime = strtotime($data['end']);
            if ($startime == $endtime) {
                $filename = $name . "_finance" . " '" . $data['start'] . "' " . date('Y-m-d H:i:s', time());
            } else {
                $filename = $name . "_finance" . " '" . $data['start'] . '--' . $data['end'] . "' " . date('Y-m-d H:i:s', time());
            }
        } else {
            $filename = $name . "_finance汇总" . date('Y-m-d H:i:s', time());
        }
        header("Content-Disposition:attachment;filename=" . $filename . ".xls"); //告诉浏览器输出的文件名
        header('Cache-Control: max-age=0'); //禁止缓存
        header("Pragma: no-cache");
        header("Expires: 0");
        //找到order里的cafe订单
        $where = "o.class = 1";
        //时间区间判断
        if (isset($startime) && isset($endtime) && $startime && $endtime) {
            if ($startime == $endtime) {
                $endtime = $startime + 86400;
                $where .= " and p.create_time > $startime and p.create_time < $endtime";
                $where_b = " and create_time > $startime and create_time < $endtime";
            } else {
                $endtime = $endtime + 86399;
                $where .= " and p.create_time > $startime and p.create_time < $endtime";
                $where_b = " and create_time > $startime and create_time < $endtime";
            }
        }
        if ($data['code'] == 'utf-8') {
            $order_id = "订单号";
            $refund_total_fee = "退款金额";
            $create_time = "创建时间";
            $total_fee_original = "原始价格";
            $discount = "折扣";
            $total_fee = "成交价";
            $discount_fee = "折扣金额";
            $user_name = "用户名";
            $admin_user_name = "操作员";
            $channel = "支付方式";
            $cashpay = "现金支付";
            $accountpay = "会员支付";
            $wxpay = "微信支付";
            $alipay = "支付宝支付";
            $introduction = "产品描述";
        } else {
            $order_id = iconv("UTF-8", "GBK//IGNORE", "订单号");
            $refund_total_fee = iconv("UTF-8", "GBK//IGNORE", "退款金额");
            $create_time = iconv("UTF-8", "GBK//IGNORE", "创建时间");
            $total_fee_original = iconv("UTF-8", "GBK//IGNORE", "原始价格");
            $discount = iconv("UTF-8", "GBK//IGNORE", "折扣");
            $total_fee = iconv("UTF-8", "GBK//IGNORE", "成交价");
            $discount_fee = iconv("UTF-8", "GBK//IGNORE", "折扣金额");
            $user_name = iconv("UTF-8", "GBK//IGNORE", "用户名");
            $admin_user_name = iconv("UTF-8", "GBK//IGNORE", "操作员");
            $channel = iconv("UTF-8", "GBK//IGNORE", "支付方式");
            $cashpay = iconv("UTF-8", "GBK//IGNORE", "现金支付");
            $accountpay = iconv("UTF-8", "GBK//IGNORE", "会员支付");
            $wxpay = iconv("UTF-8", "GBK//IGNORE", "微信支付");
            $alipay = iconv("UTF-8", "GBK//IGNORE", "支付宝支付");
            $introduction = iconv("UTF-8", "GBK//IGNORE", "产品描述");
        }
        $order = 'p.create_time desc';
        $field = "p.order_id,p.create_time,p.channel,p.total_fee,o.total_fee_original,o.detail,o.user_id,o.admin_user_id";
        $orderInfo = db('order')->alias('o')->join('pay p', 'p.order_id = o.order_id')->where($where)->field($field)->order($order)->select();
        $order_info = [];
        foreach ($orderInfo as $k => $v) {
            //处理detail数据
            $product_name = [];
            foreach (json_decode($v['detail'], 1) as $key => $value) {
                //找到detail信息
                $detail_info = Db::name('mall_detail')->field(array('detail_id', 'price','detail_code'))->where("detail_id = '$key'")->find();
                //通过detial找到option
                $product_name[] = $detail_info['detail_code'] . '*' . $value;
            }

            //订单折扣前价格
            $price = $v['total_fee_original'];
            //订单退款金额
            $refund_order_id = $v['order_id'];
            $pay_refund = db('pay_refund')->field('refund_fee')->where("order_id = '$refund_order_id'")->select();
            if ($pay_refund) {
                $refund_total = '';
                foreach ($pay_refund as $k_n => $v_n) {
                    $refund_total += $v_n['refund_fee'];
                }
                $order_info[$k][$refund_total_fee] = $refund_total / 100;
            } else {
                $order_info[$k][$refund_total_fee] = 0;
            }
            //订单简介
            if ($data['code'] != 'utf-8') {
                $order_info[$k][$introduction] = iconv("UTF-8", "GBK//IGNORE", implode(',', $product_name));
            } else {
                $order_info[$k][$introduction] = implode(',', $product_name);
            }
            //时间
            $order_info[$k][$create_time] = date("Y-m-d H:i:s", $v['create_time']);
            //订单user_name
            $user_info = model('user')->getInfoById($v['user_id']);
            $user = isset($user_info['set_name']) ? $user_info['set_name'] : userTextDecode($user_info['user_name']);
            if ($data['code'] != 'utf-8') {
                $order_info[$k][$user_name] = iconv("UTF-8", "GBK//IGNORE", $user);
            } else {
                $order_info[$k][$user_name] = $user;
            }
            $order_info[$k]['user_id'] = $v['user_id'];
            //订单admin_user_name
            $admin_user_info = model('user')->getInfoById($v['admin_user_id']);
            $admin_user = $admin_user_info['set_name'] ? $admin_user_info['set_name'] : $admin_user_info['user_name'];
            if ($data['code'] != 'utf-8') {
                $order_info[$k][$admin_user_name] = iconv("UTF-8", "GBK//IGNORE", $admin_user);
            } else {
                $order_info[$k][$admin_user_name] = $admin_user;
            }
            $order_info[$k]['admin_user_id'] = $v['admin_user_id'];
            //原始价格
            $order_info[$k][$total_fee_original] = $v['total_fee_original'] / 100;
            //最终价格
            $order_info[$k][$total_fee] = $v['total_fee'] / 100;
            //订单折扣
            if (!isset($v['discount'])) {
                $order_info[$k][$discount] = round($v['total_fee'] / $price, 2) * 10;
            }
            //折扣金额
            $order_info[$k][$discount_fee] = ($price - $v['total_fee']) / 100;
            $order_info[$k][$order_id] = $v['order_id'];
            unset($order_info[$k]['user_id']);
            //订单支付方式
            //支付渠道
            switch ($v['channel']) {
                case 1:
                    $order_info[$k][$channel] = $cashpay;
                    break;
                case 2:
                    $order_info[$k][$channel] = $accountpay;
                    break;
                default:
                    switch ((int)($v['channel'] / 100)) {
                        case 1:
                            $order_info[$k][$channel] = $wxpay;
                            break;
                        case 2:
                            $order_info[$k][$channel] = $alipay;
                            break;
                    }
            }

        }

        $order_range = array($order_id, $create_time, $introduction, $total_fee_original, $discount, $total_fee, $discount_fee, $refund_total_fee, $user_name, $admin_user_name, $channel);
        if (!$order_info) {
            $d = array();
            foreach ($order_range as $k => $v) {
                $d[$v] = strtoupper($v);
            }
            array_unshift($order_info, $d);
            if (!empty($order_info)) {
                foreach ($order_info as $key => $val) {
                    $order_info[$key] = implode("\t", str_replace("\t", " ", $order_info[$key]));
                }
                echo implode("\n", $order_info);
            }
            return;
        }
//        dump($order_info);die;
        foreach ($order_info as $k_e => $v_e) {
            foreach ($order_range as $range_key) {
                $orders[$k_e][$range_key] = $v_e[$range_key];
            }
        }
        //数据title
        $d = array();
        foreach ($orders as $k => $v) {
            foreach ($v as $kk => $vv) {
                $d[$kk] = strtoupper($kk);
            }
            break;
        }
        //合并数据
        array_unshift($orders, $d);
        if (!empty($orders)) {
            foreach ($orders as $key => $val) {
                $orders[$key] = implode("\t", str_replace("\t", " ", $orders[$key]));
            }
            echo implode("\n", $orders);
        }
    }
    //今日统计
    public function statisics($data)
    {
        header("Content-type:application/vnd.ms-excel;charset:UTF-8");
        $name = "hongyanche_" . "mall_lable";
        //找到order里的mall订单
        $where = "b.class = 1";
        if ($data['start'] && $data['end']) {
            $startime = strtotime($data['start']);
            $endtime = strtotime($data['end']);
            if ($startime == $endtime) {
                $filename = $name . "_finance" . " '" . $data['start'] . "' " . date('Y-m-d H:i:s', time());
                $endtime = $startime + 86400;
                $where .= " and p.create_time > $startime and p.create_time < $endtime";
            } else {
                $filename = $name . "_finance" . " '" . $data['start'] . '--' . $data['end'] . "' " . date('Y-m-d H:i:s', time());
                $endtime = $endtime + 86399;
                $where .= " and p.create_time > $startime and p.create_time < $endtime";
            }
        } else {
            //当前时间区间
            $todayTime = strtotime(date('Ymd'));
            $yesterday = strtotime(date('Ymd')) + 86400;
            $filename = $name . "_finance" . " '" . $todayTime . '--' . $yesterday . "' " . date('Y-m-d H:i:s', time());
            //时间区间判断
            $where .= " and p.create_time > $todayTime and p.create_time < $yesterday";
        }
        header("Content-Disposition:attachment;filename=" . $filename . ".xls"); //告诉浏览器输出的文件名
        header('Cache-Control: max-age=0'); //禁止缓存
        header("Pragma: no-cache");
        header("Expires: 0");
        //查询今日订单
        $order = Db::name('pay')
            ->alias('p')
            ->join('order b', 'p.order_id = b.order_id')
            ->join('mall_order c','c.order_id = p.order_id')
            ->where($where)
            ->field('p.order_id,p.total_fee,b.detail,c.people,c.people_min,c.user_id,c.total_fee_min')
            ->group('p.order_id')
            ->select();
        $order_ids = [];
        $dixiao = [];
        foreach ($order as $key => $value) {
            $order_ids[] = $value['order_id'];
            $dixiao[] = $value['total_fee_min'];
        }
        $dixiao_total = array_sum($dixiao)/100;
        $order_ids = implode(',', $order_ids);
        $pay_refund = [];
        $mall = [];
        if ($order_ids) {
            $mall= Db::name('mall_order')
                ->alias('a')
                ->join('mall_detail b', 'a.detail_id = b.detail_id')
                ->join('mall c', 'c.mall_id = b.mall_id')
                ->field('a.user_id,c.name,c.labels,b.price,a.amount,b.discount')
                ->where("a.order_id in($order_ids)")->select();
            $pay_refund = Db::name('pay_refund')->field('sum(refund_fee)')->where("order_id in($order_ids)")->select();
        }
        $refund_fee = $pay_refund[0]['sum(refund_fee)']/100;
        $mallInfo = [];
        foreach ($mall as $key => $value) {
            $mallInfo[$value['labels']][$value['name']]['amount'][] = $value['amount'];
            $discounts = model('member')->getDiscountByUserId('mall', $value['user_id']);
            if ($discounts['state']) {
                $discount = $discounts['info']['discount'];
            } else {
                $discount = 1;
            }
            $value['discount'] ? $value['discount'] = $value['discount']/100 : $value['discount'] = 1;
            $value['discount']<= $discount ? $discounts = $value['discount'] : $discounts = $discount;
            $mallInfo[$value['labels']][$value['name']]['total_fee'][] = $value['price'] * $discounts * $value['amount'];
            $mallInfo[$value['labels']][$value['name']]['original_fee'][] = $value['price'] * $value['amount'];

        }
        $statisics = [];
        foreach ($mallInfo as $k => $v) {
            if ($k) {
                $labels = Db::name('mall_label')->where("label_id = $k")->field('cn')->find();
            }
            $labels_name = isset($labels['cn']) ? $labels['cn'] : $k;
            $amount = 0;
            $total = 0;
            $original_fee = 0;
            foreach ($v as $key => $value) {
//                $statisics[$labels_name][array_sum($value['amount'])]['key'] = $key;
                $statisics[$labels_name][$key]['amount'] = array_sum($value['amount']);
                $statisics[$labels_name][$key]['price'] = array_sum($value['total_fee']) / 100;
                $statisics[$labels_name][$key]['original_fee'] = array_sum($value['original_fee']) / 100;
                //$statisics[$labels_name][$key]['discount'] = array_sum($value['original_fee'])/100 - array_sum($value['total_fee'])/100;
                $amount += array_sum($value['amount']);
                $total += array_sum($value['total_fee']);
                $original_fee += array_sum($value['original_fee']);
            }
            $statisics[$labels_name]['amount'] = $amount;
            $statisics[$labels_name]['total_fee'] = $total / 100;
            $statisics[$labels_name]['original_fee'] = $original_fee / 100;
            //$statisics[$labels_name]['discount_fee'] = $original_fee/100 - $total/100;
        }

        //dump($statisics);die;
        foreach ($statisics as $k => $v) {
            $id[$k] = count($v) - 3;
            $product_price[] = $v['total_fee'];
            arsort($statisics[$k]);
        }
        array_multisort(array_column($statisics, 'amount'), SORT_DESC, $statisics);
        $product_total = array_sum($product_price);
        if ($data['code'] == 'utf-8') {
            $label = "种类";
            $amountAll = "总数";
            $totalFee = "总价格(元)";
            $totalOriginalFee = "原始总价格(元)";
            $product_name = "产品名字";
            $amount = "数量";
            $price = "价格(元)";
            $originalFee = "原始价格(元)";
            $tongji = "统计";
            $dixao = "低消";
            $productTotal = "产品价格";
            $refundFee = "退款";
        } else {
            $label = iconv("UTF-8", "GBK//IGNORE", "种类");
            $amountAll = iconv("UTF-8", "GBK//IGNORE", "总数");
            $product_name = iconv("UTF-8", "GBK//IGNORE", "产品名字");
            $amount = iconv("UTF-8", "GBK//IGNORE", "数量");
            $totalFee = iconv("UTF-8", "GBK//IGNORE", "总价格(元)");
            $price = iconv("UTF-8", "GBK//IGNORE", "价格(元)");
            $originalFee = iconv("UTF-8", "GBK//IGNORE", "原始价格(元)");
            $totalOriginalFee = iconv("UTF-8", "GBK//IGNORE", "原始总价格(元)");
            $tongji = iconv("UTF-8", "GBK//IGNORE", "统计");
            $dixao = iconv("UTF-8", "GBK//IGNORE", "低消");
            $productTotal = iconv("UTF-8", "GBK//IGNORE", "产品价格");
            $refundFee = iconv("UTF-8", "GBK//IGNORE", "退款");

        }
        $table = "";
        $table .= "<table border=1 style='border-collapse: collapse'>
                            <tr>
                                <th>" . $label . "</th>
                                <th>" . $amountAll . "</th>
                                <th>" . $totalFee . "</th>
                                <th>" . $totalOriginalFee . "</th>
                                <th>" . $product_name . "</th>
                                <th>" . $amount . "</th>
                                <th>" . $price . "</th>
                                <th>" . $originalFee . "</th>
                            </tr>";
        foreach ($statisics as $k => $v) {
            if ($data['code'] == 'utf-8') {
                $key = $k;
            } else {
                $key = iconv("UTF-8", "GBK//IGNORE", $k);
            }
            $table .= "<tr>
                    <td rowspan='$id[$k]'style='text-align:center'>$key</td>
                    <td rowspan='$id[$k]'style='text-align:center'>$v[amount]</td>
                    <td rowspan='$id[$k]'style='text-align:center'>$v[total_fee]</td>
                    <td rowspan='$id[$k]'style='text-align:center'>$v[original_fee]</td>";
            unset($v['amount'], $v['total_fee'], $v['original_fee']);
            foreach ($v as $kk => $vv) {
                $style = "style=text-align:center";
                if ($data['code'] == 'utf-8') {
                    $keys = $kk;
                } else {
                    $keys = iconv("UTF-8", "GBK//IGNORE", $kk);
                }
                $table .= "<td " . $style . ">$keys</td>
                        <td " . $style . ">$vv[amount]</td>
                        <td " . $style . ">$vv[price]</td>
                        <td " . $style . ">$vv[original_fee]</td>
                        </tr>";
            }
        }
        $table .= "<tr>
                    <td colspan='5' rowspan='4' style='text-align: center'>".$tongji."</td>
                    <td rowspan='4' style='text-align: center'>".$dixiao_total."(".$dixao.")</td>
                    <td  rowspan='4' style='text-align: center'>".$product_total."(".$productTotal.")</td>
                    <td  rowspan='4' style='text-align: center'>".$refund_fee."(".$refundFee.")</td></tr>";
        $table .= "</table>";
        echo $table;
    }
    //按小时统计销售额
    public function hourExcel($data)
    {
        header("Content-type:application/vnd.ms-excel;charset:UTF-8");
        $name = "hongyanche_" . "mallTimes";
        if ($data['start'] && $data['end']) {
            $startime = strtotime($data['start']);
            $endtime = strtotime($data['end']);
            if ($startime == $endtime) {
                $filename = $name . "_finance" . " '" . $data['start'] . "' " . date('Y-m-d H:i:s', time());
            } else {
                $filename = $name . "_finance" . " '" . $data['start'] . '--' . $data['end'] . "' " . date('Y-m-d H:i:s', time());
            }
        } else {
            $filename = $name . "_finance汇总" . date('Y-m-d H:i:s', time());
        }
        header("Content-Disposition:attachment;filename=" . $filename . ".xls"); //告诉浏览器输出的文件名
        header('Cache-Control: max-age=0'); //禁止缓存
        header("Pragma: no-cache");
        header("Expires: 0");
        //时间区间判断
        if (isset($startime) && isset($endtime) && $startime && $endtime) {
            if ($startime == $endtime) {
                $endtime = $startime + 86400;
            } else {
                $endtime = $endtime + 86399;
            }
        }
        $res = Db::name('pay')
            ->alias('a')
            ->join('order b', 'a.order_id = b.order_id')
            ->where("b.class = 1 and a.create_time>=$startime and a.create_time<=$endtime")
            ->select();
        $order_id = [];
        foreach ($res as $key => $vaule) {
            $res[$key]['create_time'] = date('Y-m-d H', $vaule['create_time']);
            $order_id[] = $vaule['order_id'];
        }
        $order_ids = implode($order_id, ',');
        $refund = Db::name('pay_refund')->where("order_id in($order_ids)")->select();
        foreach ($res as $key => $vaule) {
            $res[$key]['refund_fee'] = 0;
            foreach ($refund as $k => $v) {
                if ($vaule['order_id'] == $v['order_id']) {
                    $res[$key]['refund_fee'] += $v['refund_fee'];
                }
            }
        }
        $arr = [];
        foreach ($res as $key => $vaule) {
            $arr[$vaule['create_time']]['total_fee'][] = $vaule['total_fee'];
            $arr[$vaule['create_time']]['refund_fee'][] = $vaule['refund_fee'];
        }
        $x = 0;
        foreach ($arr as $k => $v) {
            $hour[$x]['time'] = $k;
            $hour[$x]['total_fee'] = array_sum($v['total_fee']);
            $hour[$x]['refund_fee'] = array_sum($v['refund_fee']);
            $x++;
        }
        $i = 0;
        while ($startime < $endtime) {
            $tmp[$i]['time'] = date('Y-m-d H', $startime);
            $tmp[$i]['total_fee'] = 0;
            $tmp[$i]['refund_fee'] = 0;
            $i++;
            $startime = $startime + 3600;
        }
        foreach ($tmp as $h => $s) {
            foreach ($hour as $ks => $vs) {
                if ($vs['time'] == $s['time']) {
                    $tmp[$h]['total_fee'] = $vs['total_fee'] / 100;
                    $tmp[$h]['refund_fee'] = $vs['refund_fee'] / 100;
                }
            }
            $hh = (int)substr($s['time'], -2);
            if ($hh < 8) {
                unset($tmp[$h]);
            }
        }
        if ($data['code'] == 'utf-8') {
            $time = "时间";
            $total_fee = "成交额(元)";
            $refund_total_fee = "退款额(元)";
        } else {
            $time = iconv("UTF-8", "GBK//IGNORE", "时间");
            $total_fee = iconv("UTF-8", "GBK//IGNORE", "成交额(元)");
            $refund_total_fee = iconv("UTF-8", "GBK//IGNORE", "退款额(元)");
        }
        $order = [];
        foreach ($tmp as $k => $v) {
            $order[$k][$time] = $v['time'];
            $order[$k][$total_fee] = $v['total_fee'];
            $order[$k][$refund_total_fee] = $v['refund_fee'];
        }
        //数据title
        $d = array();
        foreach ($order as $k => $v) {
            foreach ($v as $kk => $vv) {
                $d[$kk] = strtoupper($kk);
            }
            break;
        }
        //合并数据
        array_unshift($order, $d);
        if (!empty($order)) {
            foreach ($order as $key => $val) {
                $order[$key] = implode("\t", str_replace("\t", " ", $order[$key]));
            }
            echo implode("\n", $order);
        }
    }
    //今日统计
    public function statisticsToday(){
        if (!$this->auth){
            return [
                'state' => 0,
                'errormsg' => 'authority incorrect'
            ];
        }
        //当前时间区间
        $begin_time = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $end_time = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        //今日订单总数
        $data['order_total_num'] = Db::table($this->prefix.'order')
            ->alias('a')
            ->join($this->prefix.'pay b','a.order_id = b.order_id')
            ->where('state','1')
            ->where('class','1')
            ->where('a.create_time','EGT',$begin_time)
            ->where('a.create_time','ELT',$end_time)
            ->count();
        //今日退款订单数量
        $record = [];
        $data['order_refund_num'] = Db::table($this->prefix.'order')
            ->alias('a')
            ->join($this->prefix.'pay_refund b','a.order_id = b.order_id')
            ->where('state','1')
            ->where('class','1')
            ->where('a.create_time','EGT',$begin_time)
            ->where('a.create_time','ELT',$end_time)
            ->count();
        //今日实际订单数量
        $data['order_reality_num'] = $data['order_total_num'] - $data['order_refund_num'];
        $order_info = Db::table($this->prefix.'pay')
            ->alias('a')
            ->join($this->prefix.'order b','a.order_id = b.order_id')
            ->where('state','1')
            ->where('class','1')
            ->where('b.create_time','EGT',$begin_time)
            ->where('b.create_time','ELT',$end_time)
            ->select();
        //dump($order_info);die();
        $statistics['total_fee'] = "";
        $statistics['refund_fee'] = "";
        foreach ($order_info as $k => $v) {
            //今日订单金额总和
            $statistics['total_fee'] += $v['total_fee'];
            //订单退款
            $order_id = $v['order_id'];
            $refund = Db::name('pay_refund')->where("order_id = '$order_id'")->select();
            $refund_order = '';
            foreach ($refund as $k_k => $v_v) {
                $refund_order += $v_v['refund_fee'];
            }
            $statistics['refund_fee'] += $refund_order;
            //支付渠道
            switch ($v['channel']) {
                case 1:
                    $record[$k]['cashpay'] = 1;
                    break;
                case 2:
                    $record[$k]['accountpay'] = 1;
                    break;
                default:
                    switch ((int) ($v['channel'] / 100)) {
                        case 1:
                            $record[$k]['wxpay'] = 1;
                            break;
                        case 2:
                            $record[$k]['alipay'] = 1;
                            break;
                    }
            }
        }
        $statistics['cash_total_fee'] = "";
        $statistics['cash_refund_fee'] = "";
        $statistics['tenpay_total_fee'] = "";
        $statistics['tenpay_refund_fee'] = "";
        $statistics['alipay_total_fee'] = "";
        $statistics['alipay_refund_fee'] = "";
        $statistics['account_total_fee'] = "";
        $statistics['account_refund_fee'] = "";
        foreach ($record as $k => $v) {
            foreach ($v as $key => $value) {
                //现金
                $refund = '';
                $cashpay_refund_id = '';
                if ($key == 'cashpay') {
                    //退款
                    $cashpay_refund_id = $order_info[$k]['order_id'];
                    $refund = Db::name('pay_refund')->where("order_id = '$cashpay_refund_id'")->select();
                    $cashpay_refund = 0;
                    foreach ($refund as $k_n => $k_v) {
                        $cashpay_refund += $k_v['total_fee'];
                    }
                    $statistics['cash_refund_fee'] += $cashpay_refund;
                    $statistics['cash_total_fee'] += $order_info[$k]['total_fee'];
                }
                //微信
                if ($key == 'wxpay') {
                    //退款
                    $cashpay_refund_id = $order_info[$k]['order_id'];
                    $refund = Db::name('pay_refund')->where("order_id = '$cashpay_refund_id'")->select();
                    $cashpay_refund = 0;
                    foreach ($refund as $k_n => $k_v) {
                        $cashpay_refund += $k_v['refund_fee'];
                    }
                    $statistics['tenpay_refund_fee'] += $cashpay_refund;
                    $statistics['tenpay_total_fee'] += $order_info[$k]['total_fee'];
                }
                //alipay
                if ($key == 'alipay') {
                    //退款
                    $cashpay_refund_id = $order_info[$k]['order_id'];
                    $refund = Db::name('pay_refund')->where("order_id = '$cashpay_refund_id'")->select();
                    $cashpay_refund = 0;
                    foreach ($refund as $k_n => $k_v) {
                        $cashpay_refund += $k_v['refund_fee'];
                    }
                    $statistics['alipay_refund_fee'] += $cashpay_refund;
                    $statistics['alipay_total_fee'] += $order_info[$k]['total_fee'];
                }
                //刷卡
                if ($key == 'accountpay') {
                    //退款
                    $cashpay_refund_id = $order_info[$k]['order_id'];
                    $refund = Db::name('pay_refund')->where("order_id = '$cashpay_refund_id'")->select();
                    $cashpay_refund = 0;
                    foreach ($refund as $k_n => $k_v) {
                        $cashpay_refund += $k_v['refund_fee'];
                    }
                    $statistics['account_refund_fee'] += $cashpay_refund;
                    $statistics['account_total_fee'] += $order_info[$k]['total_fee'];
                }
            }
        }
        return [
            'state' => 1,
            'data' => ['info'=>$statistics]
        ];
    }


    //收货地址排序
    function range($ranges)
    {
        $demand = 'mall_address';
        if (!$ranges) return ['state' => 0,'errormsg'=> 'range error'];
        $ranges = explode(",", $ranges);
        foreach ($ranges as $range => $demand_id) {
            $where = ['address_id' => $demand_id, 'state' =>1];
            $update = ['range' => $range];
            db($demand)->where($where)->update($update);
        }
        return ['state' => 1];
    }
    //收货地址列表
    public function address_list(){
        $user_id = $this->userId;
        if(!$user_id){
            return [
                'state'=>0,
                'errormsg'=>'请登录'
            ];
        }
        $where = "user_id = $user_id and state = 1";
        $order = ['default'=>'desc','range'=>'asc','create_time'=>'desc'];
        $list = Db::name('mall_address')->where($where)->order($order)->select();
        foreach ($list as $k =>$v){
            $list[$k]['addressfull'] = $v['address_province'].$v['address_city'].$v['address_district'].$v['address'];
        }
        if($list){
            return [
                'state'=>1,
                'data'=>[
                    'list'=>$list
                ]
            ];
        }
        return [
            'state'=>1,
            'data'=>[]
        ];
    }
    //创建收货地址
    public function address_create($data){
        $user_id = $this->userId;
        if(!$user_id){
            return [
                'state'=>0,
                'errormsg'=>'Parameter error'
            ];
        }
        if(!$data['address_name']){
            return array('state'=>0,'errormsg'=>'请输入姓名');
        }
        if(!$data['address_tel'] && !$data['landline']){
            return array('state'=>0,'errormsg'=>'请输入电话号码');
        }else{
            if(!preg_match('/^((0\d{2,3}-\d{7,8})|(1[35784]\d{9}))$/', $data['address_tel'])){
                return array('state'=>0,'errormsg'=>'电话号码格式错误');
            }
        }
        if(!$data['address']){
            return array('state'=>0,'errormsg'=>'请输入详细地址');
        }
        if(!$data['address_province']){
            return array('state'=>0,'errormsg'=>'请输入省市');
        }
        if(!$data['address_city']){
            return array('state'=>0,'errormsg'=>'请输入市区');
        }
//        if(!$data['address_district']){
//            return array('state'=>0,'errormsg'=>'请输入区县');
//        }
        $data['state']         = 1;
        $data['create_time']  = $_SERVER['REQUEST_TIME'];
        $data['user_id']       = $user_id;
//        dump($data);die;
        $res = Db::name('mall_address')->insertGetId($data);
        if(!$res){
            return [
                'state'=>0,
                'errormsg'=>'create false'
            ];
        }
        return array('state'=>1,'address_id'=>$res);
    }
    //设置默认收货地址
    public function address_default($address_id){
        $demand = 'mall_address';
        if (!$address_id) return ['state' => 0, '收货地址选择错误'];
        if(!$this->userId) return array('state'=>0,'errormsg'=>'请登录');
        //先清空默认收货地址
        db($demand)->where("user_id = $this->userId and state = 1")->update(['default'=>null]);
        //设置默认收货地址
        $res = db($demand)->where("user_id = $this->userId and state = 1 and address_id = $address_id")->update(['default'=>1]);
        if(!$res) return array('state'=>0,'errormsg'=>'设置失败');
        return ['state' => 1];
    }
    //删除收货地址
    public function address_remove($address_id){
        if($address_id<=0){
            return [
                'state'=>0,
                'errormsg'=>"Parameter error"
            ];
        }
        $where = "address_id = $address_id";
        $data['state'] = 0;
        $res = Db::name('mall_address')->where($where)->update($data);
        if($res){
            return [
                'state'=>1,
                'errormsg'=>'remove success'
            ];
        }
        return [
            'state'=>0,
            'errormsg'=>'remove false'
        ];
    }
    /* //收货地址编辑
     public function address_modify($address_id,$key,$content){
         $user_id = $this->userId;
         if(!$user_id){
             return [
                 'state'=>0,
                 'errormsg'=>"please login"
             ];
         }
         if($address_id<=0 || !$address_id){
             return [
               'state'=>0,
                 'errormsg'=>"Parameter error"
             ];
         }
         $data[$key] = $content;
         $where = "address_id = $address_id";
         $res = Db::name('mall_address')->where($where)->update($data);
         if($res){
             return [
               'state'=>1,
                 'errormsg'=>'update success'
             ];
         }
         return [
             'state'=>0,
             'errormsg'=>'update false'
         ];*/


    //-------------------------卡车积木--------------------------
    //通过配置查询车辆
    public function getListByConfig($config_option_id,$page){
        $res = db("mall_config")->where("state = 1")->select();
        foreach ($res as $k =>$v){
            $res[$k]['option'] = db("mall_config_option")->where("state = 1 and config_id = $v[config_id]")->select();
        }

        $mall = db("mall")->alias("m")
            ->join("mall_detail c","c.mall_id = m.mall_id")
            ->join("mall_detail_option o","o.detail_id = c.detail_id")
            ->where("o.option_name_cn like '%$config_option_id'% and m.state = 1")
            ->paginate(12,false,['page'=>$page]);
        $pages = $mall->lastPage();
        $mall = $mall->items();
        if(!$mall) return ['state'=>1,'data'=>[]];
        return ['state'=>1,'data'=>['list'=>$mall],'page'=>$pages];
    }

    //---------------------卡车积木自定义配置------------------------
    //自定义配置列表
    public function diyConfigList(){
        $diyconfig = \db("mall_diy_config")->where("state = 1")->select();
        $diyoption = \db("mall_diy_config_option")->where("state = 1")->select();
        if(model('admin')->is("mall")['state']){
            $diyconfig = \db("mall_diy_config")->where("state != 0")->select();
            $diyoption = \db("mall_diy_config_option")->where("state != 0")->select();
        }
        foreach ($diyconfig as $k =>$v){
            foreach ($diyoption as $kk =>$vv){
                if($v['config_id'] == $vv['config_id']){
                    $diyconfig[$k]['option'][] = $vv;
                }
            }
        }
        if(!$diyconfig) return ['state'=>1,'data'=>[]];
        return ['state'=>1,'data'=>['list'=>$diyconfig]];
    }

    //增加配置
    public function diyConfigAdd($data)
    {
        if(!$data['diycontent']) return ['state'=>0,'errormsg'=>'参数错误'];
        try{
            $data['diy_content'] = json_decode($data['diycontent'],1);
        }catch (Exception $e){
            return['state'=>0,'errormsg'=>'参数错误'];
        }
        $_data['create_time'] = time();
    }
    //增加删除配置
    public function diyConfigRemove($data)
    {

    }
    //修改配置
    public function diyConfigModify($data)
    {

    }

    //用户提交自定义配置
    public function diyConfigByUser($data)
    {
        if(!$this->userId) return ['state'=>0,'errormsg'=>'请登录'];
        if(!$data['diycontent']) return ['state'=>0,'errormsg'=>'请选择自定义参数'];
        try{
            $data['diycontent'] = json_decode($data['diycontent'],1);
        }catch (Exception $e){
            return ['state'=>0,'errormsg'=>'参数错误'];
        }
        $_data['diy_content'] = $data['diycontent'];
        $_data['user_id'] = $this->userId;
        $_data['state'] = 1;
        $_data['create_time'] = time();
        $res = \db("mall_diy_user")->insert($_data);
        if(!$res) return ['state'=>0,'errormsg'=>'自定义失败,请重新选择'];
        return ['state'=>1,'errormsg'=>'保存成功'];
    }


}